import sys, os

sys.path.append(os.path.abspath('..'))
from inference import run_onnx_model

#sys.path.append(os.path.abspath('../analyze'))
from analyze import analyze

class Base:
    success_flag = 'Convert Success!'

    def analyze_and_inference(self, test_case, option, output, succcess_list, failed_list, **params):
        print(test_case + ' convert success')
        inference = params['inference']
        r = analyze.analyze_method[option](output, **params)
        if r == True:
            if inference == True:
                r = run_onnx_model(output)

            if r == True:
                print(test_case + 'run model successful')
                succcess_list.append(test_case)
            else:
                f = {}
                f['case'] = test_case
                f['phase'] = 'inference'
                failed_list.append(f)
        else:
            f = {}
            f['case'] = test_case
            f['phase'] = 'analyze'
            failed_list.append(f) 

    def test_model2onnx(self, tool_path, test_case, cmd, output, succcess_list, failed_list, input_npy='', output_npy=''):
        cwd = os.getcwd()

        os.chdir(tool_path)

        os.system(cmd)

        os.chdir(cwd)

        log_file = open('./convert.log','r')
        content = log_file.readline()
        #print('log content:', content)

        if self.success_flag in content:
            print(test_case + ' success')
            r = run_onnx_model(output, input_npy, output_npy, test_case)
            if r == True:
                print('Run model successful-----')
                #logger.info()
                succcess_list.append(test_case)
            else:
                f = {}
                f['case'] = test_case
                f['phase'] = 'inference'
                failed_list.append(f)
        else:
            f = {}
            f['case'] = test_case
            f['phase'] = 'convert'
            failed_list.append(f)     

        log_file.close()

    def clear(self):
        cwd = os.getcwd()
        output = os.path.join(cwd, './tmp.onnx')
        os.remove(output)

    def mx_copy(self, a, b):
        with open(a, "r", encoding="utf-8") as fp:
            a = fp.readlines()
            with open(b, "w", encoding="utf-8") as fp1:
                    fp1.writelines(a)
